/**
 * 课程管理
 */

<template>
  <div class="courseBox">
    <div class="courseBoxTop">
      <div class="courseBoxTopSearch">
        <div class="courseName">
          <span>课程名称：</span>
          <el-input v-model="courseName" placeholder="请输入课程名称" />
        </div>
        <div class="profession">
          <span>所属专业：</span>
          <el-select v-model="profession" placeholder="请选择所属专业">
            <el-option
              v-for="(item, index) in majorList"
              :key="index"
              :label="item.majorName"
              :value="item.majorId"
            >
            </el-option>
          </el-select>
        </div>
        <div class="version">
          <span>课程类型：</span>
          <el-select v-model="type" placeholder="请选择课程类型">
            <el-option
              :label="item.typeName"
              :value="item.typeId"
              v-for="(item, index) in courseTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </div>

        <div class="searchAndReset">
          <el-button class="searchBtn" @click="searchInput">
            <i class="el-icon-search"></i>
            <span>搜索</span>
          </el-button>
          <el-button class="resetBtn" @click="refreshInput">
            <i class="el-icon-refresh"></i>
            <span>重置</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 管理列表 -->
    <div class="courseBoxBottom">
      <div class="bottomHeader">
        <span class="title">管理列表</span>
        <div class="bottomHeaderBtn">
          <el-button class="addBtn" @click="openAddCourse">
            <i class="el-icon-plus"></i>
            <span>新增</span>
          </el-button>
          <el-button class="delBtn" @click="batchDelCourse">
            <i class="el-icon-close"></i>
            <span>批量删除</span>
          </el-button>
          <el-button class="toLeadBtn" @click.stop="setIsMaskOpen">
            <i class="icon iconfont icon-daoru"></i>
            <span>批量导入</span>

            <!-- 弹框 -->
            <div
              class="toLeadBtnMask"
              v-if="isMask"
              @mouseenter="setIsMaskOpen"
              @mouseleave="setIsMaskClose"
            >
              <span class="sanjiao"></span>
              <div class="ul">
                <el-upload
                  class="upload-demo"
                  name="file"
                  action="action"
                  :http-request="handlePreview"
                >
                  <div class="li">
                    <i></i>
                    <el-button size="small" type="primary" class="importCourse">
                      导入课程数据
                    </el-button>
                  </div>
                </el-upload>

                <div class="li">
                  <i></i>
                  <span>下载导入模板</span>
                </div>
              </div>
            </div>
          </el-button>

          <el-button class="exportBtn" @click="exportCourse">
            <i class="icon iconfont icon-daochu"></i>
            <span>导出数据</span>
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <div class="bottomMian">
        <el-table
          ref="multipleTable"
          :data="courseList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50"> </el-table-column>
          <el-table-column
            type="index"
            label="序号"
            width="50"
          ></el-table-column>
          <el-table-column prop="courseName" label="课程名称">
          </el-table-column>
          <el-table-column prop="majorName" label="所属专业"></el-table-column>
          <el-table-column
            prop="courseTypeName"
            label="课程类型"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="添加时间"
            min-width="150"
          ></el-table-column>
          <el-table-column
            prop="instructionalVersion"
            label="教学资源"
          ></el-table-column>
          <el-table-column label="启用状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#C2C2C2"
                @change="updateIsUsing(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="action" label="操作">
            <template slot-scope="scope">
              <span
                class="icon"
                @click="editCourse(scope.row)"
              >编辑</span>
              <span
                class="icon"
                @click="delCourse(scope.row.courseId)"
              >删除</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination" v-if="courseList.length > 0">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            prev-text="上一页"
            next-text="下一页"
            layout=" prev, pager, next"
            :total="total"
          >
          </el-pagination>
          <div class="jumper">
            跳到第
            <input type="text" ref="currentPage" value="1" />
            页
          </div>
          <button class="submit" @click="goPage">确定</button>
        </div>
      </div>
    </div>

    <!-- 新增课程 -->
    <div class="dialog">
      <el-dialog
        :title="isEdit ? '编辑课程' : '添加课程'"
        :visible.sync="dialogFormVisible"
        center
      >
        <el-form :model="form" ref="courseForm">
          <el-form-item label="课程名称:" :label-width="formLabelWidth">
            <el-input
              v-model="form.courseName"
              autocomplete="off"
              placeholder="请输入课程名称"
              style="width: 280px"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属专业:" :label-width="formLabelWidth">
            <el-select
              v-model="form.majorId"
              placeholder="请选择所属专业"
              style="width: 280px"
            >
              <el-option
                :label="item.majorName"
                :value="item.majorId"
                v-for="(item, index) in majorList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程类型:" :label-width="formLabelWidth">
            <el-select
              v-model="form.courseType"
              placeholder="请选择课程类型"
              style="width: 280px"
              @change="setCourseTypeName"
            >
              <el-option
                :label="item.typeName"
                :value="item.typeId + ',' + item.typeName"
                v-for="(item, index) in courseTypeList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教学资源:" :label-width="formLabelWidth">
            <el-select
              v-model="form.instructionalVersion"
              placeholder="请选择教学资源"
              style="width: 280px"
            >
              <el-option
                :label="item.typeName"
                :value="item.typeName"
                v-for="(item, index) in instructionalVersionList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAddCourse">取 消</el-button>
          <el-button type="primary" @click="confirmAddCourse">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "@/styles/picture.scss";
import { _debounce } from "@/utils/debounce";

import {
  exportApi,
  importApi,
  getMajorListApi,
  getCourseListApi,
  addCourseListApi,
  delCourseListApi,
  updateCourseListApi,
  getCourseTypeListApi,
} from "@/api/basics/course";
export default {
  data() {
    return {
      courseList: [],
      majorList: [],
      courseTypeList: [],
      total: 0,
      courseName: "",
      profession: "",
      type: "",
      multipleSelection: [],
      currentPage: 1,
      isMask: false,
      pageSize: 10,
      dialogFormVisible: false,
      instructionalVersionList: [],
      form: {
        courseType: "",
        courseId: "",
        courseName: "",
        majorId: "",
        courseTypeId: "",
        instructionalVersion: "",
        courseTypeName: "",
      },
      formLabelWidth: "100px",
      isEdit: false,
      filename: "课程管理表",
    };
  },

  mounted() {
    // 获取课程列表
    this.getCourseList({ pageNum: this.currentPage, pageSize: this.pageSize });

    // 获取所属专业列表
    getMajorListApi().then((res) => {
      this.majorList = res.data.filter((item) => {
        return item.status == "0";
      });
    });

    // 获取课程类型列表
    getCourseTypeListApi({ parentId: 63 }).then((res) => {
      this.courseTypeList = res.rows;
    });

    // 获取教学资源列表
    getCourseTypeListApi({ parentId: 176 }).then((res) => {
      this.instructionalVersionList = res.rows;
    });
  },

  methods: {
    setCourseTypeName(data) {
      this.form.courseTypeName = data.split(",")[1];
      this.form.courseTypeId = data.split(",")[0];
    },

    //  获取课程列表  / 搜索
    getCourseList(data) {
      getCourseListApi(data).then((result) => {
        if (result.code === 200) {
          this.courseList = result.rows.map((item) => {
            return {
              ...item,
              status: item.status == "0" ? true : false,
            };
          });
          this.total = result.total;
        }
      });
    },

    // 搜索
    searchInput: _debounce(function () {
      let data = {
        courseName: this.courseName,
        majorId: this.profession,
        courseTypeId: this.type,
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      };
      this.getCourseList(data);
    }, 200),

    // 重置
    refreshInput: _debounce(function () {
      this.courseName = "";
      this.profession = "";
      this.type = "";
      this.getCourseList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    }, 200),

    // 新增课程
    openAddCourse() {
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.form = {
        courseId: "",
        courseName: "",
        majorId: "",
        courseTypeId: "",
        instructionalVersion: "",
      };
    },

    // 取消新增
    closeAddCourse() {
      this.dialogFormVisible = false;
    },

    // 确定新增 / 编辑
    confirmAddCourse: _debounce(function () {
      let { courseName, majorId, courseTypeId, instructionalVersion } =
        this.form;
      if (courseName && majorId && courseTypeId && instructionalVersion) {
        this.dialogFormVisible = false;
        if (this.isEdit) {
          updateCourseListApi(this.form).then((res) => {
            if (res.code === 200) {
              this.$message.success("修改成功!");
              this.getCourseList({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
              });
            } else {
              this.$message.error("修改失败!");
            }
          });
        } else {
          addCourseListApi({ ...this.form, status: "0" }).then((res) => {
            if (res.code === 200) {
              this.$message.success("添加成功!");
              this.getCourseList({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
              });
            } else {
              this.$message.error("添加失败!");
            }
          });
        }
      } else if (!courseName) {
        this.$message.error("课程名称不能为空！");
      } else if (!majorId) {
        this.$message.error("所属专业不能为空！");
      } else if (!courseTypeId) {
        this.$message.error("课程类型不能为空！");
      } else if (!instructionalVersion) {
        this.$message.error("教学版本不能为空！");
      }
    }, 200),

    // 删除
    delCourse(ids) {
      this.$confirm("此操作将删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delCourseListApi({ ids }).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功!");
              this.getCourseList({
                pageNum: this.currentPage,
                pageSize: this.pageSize,
              });
            } else {
              this.$message.error("删除失败!");
            }
          });
        })
        .catch(() => {});
    },

    // 批量删除
    batchDelCourse() {
      if (this.multipleSelection.length) {
        let data = [...this.multipleSelection].map((item) => {
          return "" + item.courseId;
        });
        this.$confirm("此操作将删除已选择的课程, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delCourseListApi({ ids: data.join(",") }).then((res) => {
              if (res.code === 200) {
                this.$message.success("删除成功!");
                this.getCourseList({
                  pageNum: this.currentPage,
                  pageSize: this.pageSize,
                });
              } else {
                this.$message.error("删除失败!");
              }
            });
          })
          .catch(() => {});
      } else {
        this.$message.error("请选择要删除的课程！");
      }
    },

    // 修改
    editCourse(data) {
      console.log(data);
      this.isEdit = true;
      this.dialogFormVisible = true;
      let {
        courseId,
        courseName,
        majorId,
        courseTypeId,
        courseTypeName,
        instructionalVersion,
      } = data;

      this.form = {
        courseId,
        courseName,
        majorId,
        courseTypeId,
        courseTypeName,
        courseType: courseTypeId + "," + courseTypeName,
        instructionalVersion,
      };
    },

    // 修改启用状态
    updateIsUsing(data) {
      let { courseId, status } = data;
      updateCourseListApi({
        courseId,
        status: status ? "0" : "1",
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("修改成功!");
          this.dialogFormVisible = false;
          this.getCourseList({
            pageNum: this.currentPage,
            pageSize: this.pageSize,
          });
        } else {
          this.$message.error("修改失败!");
        }
      });
    },

    // 打开导入弹框
    setIsMaskOpen() {
      this.isMask = true;
    },

    // 关闭导入弹框
    setIsMaskClose() {
      this.isMask = false;
    },

    // 导出
    exportCourse() {
      this.$confirm("是否导出全部数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          exportApi().then((res) => {
            if (!res) return;
            const blob = new Blob([res], {
              type: "application/vnd.ms-excel",
            }); // 构造一个blob对象来处理数据，并设置文件类型
            if (window.navigator.msSaveOrOpenBlob) {
              //兼容IE10
              navigator.msSaveBlob(blob, this.filename);
            } else {
              const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
              const a = document.createElement("a"); //创建a标签
              a.style.display = "none";
              a.href = href; // 指定下载链接
              a.download = this.filename; //指定下载文件名
              a.click(); //触发下载
              URL.revokeObjectURL(a.href); //释放URL对象
            }
          });
        })
        .catch(() => {});
    },

    // 导入上传
    handlePreview(files) {
      let formData = new FormData();
      formData.append("file", files.file);
      importApi(formData).then((res) => {
        console.log(res);
      });
    },

    // 选择 / 全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 更改当前页码
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCourseList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },

    // 跳转当前页
    goPage() {
      let { value } = this.$refs.currentPage;
      this.currentPage = Number(value);
      this.getCourseList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.courseBoxTopSearch {
  ::v-deep .el-input__inner {
    height: 36px;
    line-height: 36px;
  }
}

.action {
  cursor: pointer;
}

.dialog {
  ::v-deep .el-dialog {
    max-width: 750px;
    min-width: 500px;
    border-radius: 10px;
    background-color: #f9f9f9;
  }

  ::v-deep .el-dialog__header {
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    background-color: #4895db;
    padding: 0;
    border-radius: 10px 10px 0 0;

    span {
      font-size: 16px;
      color: #fff;
    }
  }

  ::v-deep .el-dialog__headerbtn {
    top: 15px;
  }

  ::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
    font-size: 18px;
  }

  ::v-deep .el-dialog--center .el-dialog__body {
    text-align: initial;
    display: flex;
    justify-content: center;
  }

  ::v-deep .el-input__inner {
    height: 30px;
    line-height: 30px;
  }

  ::v-deep .el-form-item__content {
    width: 300px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }

  ::v-deep .el-dialog__footer {
    padding: 10px 20px 50px;
  }

  ::v-deep .el-button--default {
    width: 130px;
    border-radius: 20px;
    background-color: #f0f0f0;
    color: #aaaaaa;
    border: none;
  }

  ::v-deep .el-button + .el-button {
    width: 130px;
    border-radius: 20px;
    margin-left: 50px;
    background-color: #4895db;
    border-color: #4895db;
  }
}
</style>